<?php

/**
 * Zend_Db_Table auth adapter
 *
 * @author     Mon Zafra <monzee at gmail>
 * @copyright  (c)2009 Mon Zafra
 * @category   Mz
 * @package
 * @license    http://mz-project.googlecode.com/svn/trunk/LICENSE    MIT License
 * @version    SVN: $Id: Zdt.php 43 2009-05-18 11:54:11Z monzee $
 */
class Admin_Model_Auth_Zdt extends Zend_Auth_Adapter_DbTable
{
    protected $_aclModel;
    
    /**
     * Constructor. Pulls columns from config.
     *
     * @param string $username
     * @param string $password
     */
    public function __construct($username = null, $password = null)
    {
        $db = Admin_Bootstrap::getDbAdapter();
        $config = Admin_Bootstrap::getConfig('auth')->db;

        $table = $config->get('table', 'members');
        $identity = $config->get('identity', 'username');
        $credential = $config->get('credential', 'password');
        $credTreatment = $config->get('treatment', null);

        $this->_identity = $username;
        $this->_credential = $password;
        parent::__construct($db, $table, $identity, $credential, $credTreatment);
    }

    public function authenticate()
    {
        $result = parent::authenticate();
        if (Zend_Auth_Result::SUCCESS == $result->getCode()) {
            return new Zend_Auth_Result(
                Zend_Auth_Result::SUCCESS,
                $this->_createIdentity(),
                $result->getMessages()
            );
        }
        return $result;
    }

    /**
     *
     * @return Admin_Model_Acl_Adapter
     */
    public function getAclModel()
    {
        if (null === $this->_aclModel) {
            $this->_aclModel =
                Zend_Controller_Action_HelperBroker::getStaticHelper('AccessManager')
                                                   ->getAclModel()
                                                   ->getAdapter();
        }
        return $this->_aclModel;
    }

    /**
     *
     * @param Admin_Model_Acl_Adapter $model
     * @return Admin_Model_Auth_Array
     */
    public function setAclModel(Admin_Model_Acl_Adapter $model)
    {
        $this->_aclModel = $model;
        return $this;
    }

    protected function _createIdentity()
    {
        $row = (array) $this->getResultRowObject(null, 'password');
        $userRoles = $this->getAclModel()->getUserRoles($row);
        $row['roles'] = array();
        foreach ($userRoles as $role) {
            $row['roles'][] = $role['id'];
        }
        return new Admin_Model_Auth_Identity($row);
    }


}